<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{UserWithdrawRecord, User, UserBalanceFlow};
use app\service\{WechatService, AlipayService}; 
use think\facade\{Db, Log};
use think\Request;

class WithdrawController extends BaseController
{
    /**
     * 获取用户提现申请列表
     */
    public function list(Request $request) 
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            // 时间范围筛选
            if (!empty($params['start_time'])) {
                $where[] = ['create_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['create_time', '<=', $params['end_time']];
            }
            
            $list = UserWithdrawRecord::where($where)
                ->with(['user'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取用户提现申请列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 审核用户提现申请
     */
    public function audit(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            if (empty($params['withdraw_no']) || !isset($params['status'])) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }
            
            // 获取提现记录
            $record = UserWithdrawRecord::where([
                'withdraw_no' => $params['withdraw_no'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$record) {
                return json(['code' => 1, 'msg' => '提现记录不存在']);
            }
            
            if ($record->status != 0) {
                throw new \Exception('提现记录状态错误');
            }
            
            $user = User::find($record->user_id);
            
            // 审核通过
            if ($params['status'] == 1) {
                // 自动打款
                if ($record->withdraw_account_type == 1) { // 微信零钱
                    $wechatService = new WechatService($merchant_id);
                    $result = $wechatService->transfer([
                        'openid' => $user->openid,
                        'amount' => $record->withdraw_amount * 100,
                        'desc' => '用户提现'
                    ]);
                    if (!$result) {
                        throw new \Exception('微信打款失败');
                    }
                } else if ($record->withdraw_account_type == 2) { // 支付宝
                    $alipayService = new AlipayService($merchant_id);
                    $result = $alipayService->transfer([
                        'account' => $record->withdraw_account,
                        'real_name' => $record->withdraw_name,
                        'amount' => $record->withdraw_amount,
                        'remark' => '用户提现'
                    ]);
                    if (!$result) {
                        throw new \Exception('支付宝打款失败');
                    }
                }
                
                // 更新提现记录
                $record->save([
                    'status' => 2, // 已打款
                    'audit_time' => date('Y-m-d H:i:s'),
                    'audit_user_id' => $request->user_id,
                    'audit_remark' => $params['remark'] ?? ''
                ]);
                
                // 扣除冻结余额
                $user->save([
                    'frozen_balance' => Db::raw('frozen_balance-' . $record->withdraw_amount)
                ]);
                
                // 更新资金流水
                UserBalanceFlow::where('order_no', $record->withdraw_no)->update([
                    'status' => 1 // 已完成
                ]);
            }
            // 审核拒绝
            else {
                // 更新提现记录
                $record->save([
                    'status' => 3, // 已拒绝
                    'audit_time' => date('Y-m-d H:i:s'),
                    'audit_user_id' => $request->user_id,
                    'audit_remark' => $params['remark'] ?? ''
                ]);
                
                // 解冻余额
                $user->save([
                    'balance' => Db::raw('balance+' . $record->withdraw_amount),
                    'frozen_balance' => Db::raw('frozen_balance-' . $record->withdraw_amount)
                ]);
                
                // 更新资金流水
                UserBalanceFlow::where('order_no', $record->withdraw_no)->update([
                    'status' => 2 // 已取消
                ]);
            }
            
            Db::commit();
            return json(['code' => 0, 'msg' => '审核成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('审核用户提现申请失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 